﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;

using RaisingStudio.SmallProgram.Library.Internal;

namespace RaisingStudio.SmallProgram.Library
{
    [SmallProgramType]
    public static class Flickr
    {
        private const string _apiKey = "MWY5ZmI5ODE4Mjk2NzAwNTgwYmYzMzQwMjc5MzQ2YjY=";
        private static string _cachedTag;
        private static XDocument _cachedTagDocument;
        private static int _cachedTagDocumentHitCount;
        private static string _picUrlTemplate = "http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg";
        private static string _urlTemplate = "http://api.flickr.com/services/rest/?sort=interestingness-desc&safe_search=1&license=1,2,3,4,5,6,7&api_key=";

        static Flickr()
        {
            byte[] bytes = Convert.FromBase64String("MWY5ZmI5ODE4Mjk2NzAwNTgwYmYzMzQwMjc5MzQ2YjY=");
            _urlTemplate = _urlTemplate + Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        }

        public static Primitive GetPictureOfMoment()
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            string url = string.Format("{0}&method=flickr.photos.getRecent&per_page=50&page={1}", _urlTemplate, random.Next(10) + 1);
            Thread.Sleep(1000);
            return GetRandomPhotoNodeUrl(RestHelper.GetContents(url));
        }

        private static string GetRandomPhotoNodeUrl(XDocument document)
        {
            string result = null;
            if (document == null)
            {
                return "";
            }
            try
            {
                IEnumerable<XElement> source = document.Descendants("photo");
                Random random = new Random((int)DateTime.Now.Ticks);
                XElement element = source.ElementAt<XElement>(random.Next(source.Count<XElement>()));

                result = string.Format(_picUrlTemplate, new object[] { element.Attribute("farm").Value, element.Attribute("server").Value, element.Attribute("id").Value, element.Attribute("secret").Value });
            }
            catch
            {
            }
            return result;
        }

        public static Primitive GetRandomPicture(Primitive tag)
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            if (tag == _cachedTag && _cachedTagDocument != null && _cachedTagDocumentHitCount < 10)
            {
                _cachedTagDocumentHitCount++;
                return GetRandomPhotoNodeUrl(Flickr._cachedTagDocument);
            }
            string url = string.Format("{0}&method=flickr.photos.search&per_page=50&tags={1}&page={2}", _urlTemplate, tag, random.Next(10) + 1);
            Thread.Sleep(1000);
            _cachedTag = tag;
            _cachedTagDocument = RestHelper.GetContents(url);
            _cachedTagDocumentHitCount = 0;
            return GetRandomPhotoNodeUrl(_cachedTagDocument);

        }
    }
}

